import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:jicaimao_flutter/entity/minebean.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/utils/event_bus.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/sp_key.dart';
import 'package:jicaimao_flutter/utils/sp_utils.dart';
import 'package:jicaimao_flutter/views/mine/AboutUs.dart';
import 'package:jicaimao_flutter/views/mine/HelpCentre.dart';
import 'package:jicaimao_flutter/views/mine/MyFortuneBag.dart';
import 'package:jicaimao_flutter/views/mine/my_treasure_box.dart';
import 'package:jicaimao_flutter/views/mine/login_page.dart';
import 'package:jicaimao_flutter/views/mine/mymessages_page.dart';
import 'package:jicaimao_flutter/views/mine/SecurityCentre.dart';
import 'package:jicaimao_flutter/views/mine/version_update.dart';
import 'package:jicaimao_flutter/views/mine/my_nickname.dart';
import 'package:jicaimao_flutter/views/mine/personal_information_page.dart';

class MinePage extends StatefulWidget {
  @override
  MyPage createState() => MyPage();
}

class MyPage extends State<MinePage> {
  var mTotalAssets;

  var mCapital;

  var mEarnings;

  String mNickName = "";

  var mHeadImgUrl;

  String userId;

  var mText_Authentication;

  EventBus eventBus = new EventBus();


  List<String> nameItems = <String>['微信', '朋友圈', '新浪微博', 'QQ'];
  List<String> urlItems = <String>[
    'icon_share_wechata.png',
    'icon_share_wxcircle.png',
    'icon_share_sina.png',
    'icon_share_qq.png'
  ];

  @override
  void initState() {
    super.initState();
    userId = SpUtils.getString(SpKey.KEY_USER_ID);

    if (userId.length != 0) {
      // 网络请求数据
      _loadData(userId);
    } else {
      mTotalAssets = "0000.0000";
      mCapital = "0000.0000";
      mEarnings = "0000.0000";
      mNickName = "我的";
      mText_Authentication = "登录 | 注册";
    }

    eventBus.on<MyEvent>().listen((MyEvent data) =>
        show(data.text));
    print("666666 text:");
  }

  void show(String name) {
    setState(() {
      mNickName=name;
      _loadData(userId);
      print("666666 mNickName:" + mNickName);
      print("666666 val:" + name);
    });
  }

  static SlideTransition createTransition(
      Animation<double> animation, Widget child) {
    return new SlideTransition(
      position: new Tween<Offset>(
        begin: const Offset(1.0, 0.0),
        end: const Offset(0.0, 0.0),
      ).animate(animation),
      child: child,
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color(0xFFF1F1F1),
        body: SingleChildScrollView(
          reverse: false,
          child: Center(
            child: new Column(
              children: [
                new Stack(children: <Widget>[
                  new Image.asset(
                    'images/icon_dh.png',
                  ),

                  new Image.asset(
                    'images/icon_violet2.png',
                    height: 90,
                  ),

                  new Image.asset(
                    'images/icon_violet2.png',
                    height: 143,
                  ),
                  new Image.asset(
                    'images/icon_violet.png',
                    height: 300,
                  ),

                  ///设置
                  _Set(context),
                  ///头像背景
                  new Positioned(
                    left: 20.2,
                    top: 65.0,
//                    top: 76.4,
                    child: GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => LoginPage()),
                        );
                      },
                      child: Image.asset(
                        'images/icon_user_head.png',
                        fit: BoxFit.contain,
                        height: 100.0,
                        width: 100.0,
                      ),
                    ),
                  ),

                  ///头像
                  _Head(context),

                  ///用户名
                  new Align(
                    alignment: Alignment.center,
                    heightFactor: 3.5,
                    child: Text(
                      mNickName.toString(),
                      style: new TextStyle(
                        fontSize: 20.0,
                        color: Colors.white,
                        fontFamily: 'serif',
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ),

                  ///身份认证
                  _Authentication(context),

                  ///我的消息
                  _Mymessages(context),

                  Positioned(
                      left: 9.0,
                      top: 187.0,
                      right: 9.0,
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          Expanded(
                            child: Container(
                                color: Colors.white,
                                width: 108.0,
                                height: 95.0,
                                child: Column(
                                  children: <Widget>[
                                    new Text(
                                      null != mTotalAssets
                                          ? mTotalAssets.toString()
                                          : '0.0000',
//                                      '0000.0000',
                                      textAlign: TextAlign.center,
                                      style: new TextStyle(
                                        fontSize: 16.0,
                                        height: 2.0,
                                        fontWeight: FontWeight.normal,
                                        color: Color(0xFFFF543E),
                                        fontFamily: 'serif',
                                      ),
                                    ),
                                    new Text(
                                      '总资产(BSC)',
                                      textAlign: TextAlign.center,
                                      style: new TextStyle(
                                        fontSize: 13.0,
                                        height: 1.5,
                                        fontWeight: FontWeight.normal,
                                        color: Color(0xFF666666),
                                        fontFamily: 'serif',
                                      ),
                                    ),
                                  ],
                                )),
                            flex: 1,
                          ),
                          Expanded(
                            child: Container(
                                color: Colors.white,
                                margin: EdgeInsets.fromLTRB(9.0, 0.0, 0.0, 0.0),
                                width: 108.0,
                                height: 95.0,
                                child: Column(
                                  children: <Widget>[
                                    new Text(
                                      null != mCapital
                                          ? mCapital.toString()
                                          : '0000.0000',
                                      textAlign: TextAlign.center,
                                      style: new TextStyle(
                                        fontSize: 16.0,
                                        height: 2.0,
                                        color: Color(0xFFAD5AFE),
                                        fontWeight: FontWeight.normal,
                                        fontFamily: 'serif',
                                      ),
                                    ),
                                    new Text(
                                      '已申购(BSC)',
                                      textAlign: TextAlign.center,
                                      style: new TextStyle(
                                        fontSize: 13.0,
                                        height: 1.5,
                                        fontWeight: FontWeight.normal,
                                        color: Color(0xFF666666),
                                        fontFamily: 'serif',
                                      ),
                                    ),
                                  ],
                                )),
                            flex: 1,
                          ),
                          Expanded(
                            child: Container(
                                color: Colors.white,
                                width: 108.0,
                                height: 95.0,
                                margin: EdgeInsets.fromLTRB(9.0, 0.0, 0.0, 0.0),
                                child: Column(
                                  children: <Widget>[
                                    new Text(
                                      null != mEarnings
                                          ? mEarnings.toString()
                                          : '0.0000',
                                      textAlign: TextAlign.center,
                                      style: new TextStyle(
                                        fontSize: 16.0,
                                        height: 2.0,
                                        fontWeight: FontWeight.normal,
                                        color: Color(0xFFFFA000),
                                        fontFamily: 'serif',
                                      ),
                                    ),
                                    new Text(
                                      '账户余额(BSC）',
                                      textAlign: TextAlign.center,
                                      style: new TextStyle(
                                        fontSize: 13.0,
                                        height: 1.5,
                                        fontWeight: FontWeight.normal,
                                        color: Color(0xFF666666),
                                        fontFamily: 'serif',
                                      ),
                                    ),
                                  ],
                                )),
                            flex: 1,
                          ),
                        ],
                      )),
                ]),

                //条目
                new Column(children: [
                  commentTitle(
                      context, 0, '我的宝箱', "images/icon_my_treasure_box.png"),
                  GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => MyFortuneBag()),
                      );
                    },
                    child: Container(
                      margin: EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
                      height: 45.0,
                      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
                      color: Colors.white,
                      child: new Row(
                        children: <Widget>[
                          new Image.asset(
                            "images/img_bar.png",
                            width: 30.0,
                            height: 30.0,
                          ),
                          Expanded(
                            child: new Text('我的福袋',
                                style: new TextStyle(
                                    fontWeight: FontWeight.normal,
                                    fontSize: 15.0,
                                    color: Colors.red)),
                            flex: 1,
                          ),
                          new Image.asset(
                            "images/icon_more.png",
                            width: 10.0,
                            height: 10.0,
                          ),
                        ],
                      ),
                    ),
                  ),
                  commentTitle(
                      context, 1, '安全中心', "images/icon_security_center.png"),
                  commentTitle(
                      context, 2, '帮助中心', "images/icon_help_center.png"),
                  commentTitle(context, 3, '分享APP', "images/icon_share.png"),
                  commentTitle(context, 4, '关于我们', "images/icon_about_us.png"),
                  commentTitle(
                      context, 5, '版本更新', "images/icon_version_update.png"),
                ]),
              ],
            ),
          ),
        ),
      ),
    );
  }

  ///我的认证
  Widget _Authentication(BuildContext context) {
    return new Positioned(
      left: 140.0,
      top: 105.0,
      child: GestureDetector(
        onTap: () {
          if (userId.length == 0) {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => LoginPage()),
            );
          }
        },
        child: new Text(
          mText_Authentication.toString(),
          style: new TextStyle(
            fontSize: 14.0,
            color: Colors.white,
            fontWeight: FontWeight.normal,
            fontFamily: 'serif',
          ),
        ),
      ),
    );
  }

  ///头像
  Widget _Head(BuildContext context) {
    return new Positioned(
      left: 30.15,
      top: 74.9,
      child: GestureDetector(
        child: ClipOval(
          child: FadeInImage.assetNetwork(
            placeholder: 'images/icon_user_head.png',
            image: mHeadImgUrl.toString(),
            height: 80.0,
            width: 80.0,
            fit: BoxFit.cover,
          ),
        ),
        onTap: () {
          if (userId.length != 0) {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => MersonalInformationPage()),
            );
          } else {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => LoginPage()),
            );
          }
        },
      ),
    );
  }

  ///设置
  Widget _Set(BuildContext context) {
    return new Positioned(
      left: 21.2,
      top: 36.4,
      child: GestureDetector(
        child: Image.asset(
          'images/icon_set.png',
        ),
        onTap: () {
          if (userId.length != 0) {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => MersonalInformationPage()),
            );
          } else {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => LoginPage()),
            );
          }
        },
      ),
    );
  }

  ///我的消息
  Widget _Mymessages(BuildContext context) {
    return new Positioned(
      right: 25.0,
      top: 35.0,
      child: GestureDetector(
        onTap: () {
          if (userId.length != 0) {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => MymessagesPage()),
            );
          } else {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => LoginPage()),
            );
          }
        },
        child: new Image.asset(
          'images/icon_messages.png',
          width: 20.0,
          height: 20.0,
        ),
      ),
    );
  }

  Widget commentTitle(
      BuildContext context, int type, String title, String icon) {
    return new GestureDetector(
        child: Container(
          height: 45.0,
          padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
          margin: EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
          color: Colors.white,
          child: Row(
            children: <Widget>[
              new Image.asset(
                icon,
                width: 30.0,
                height: 30.0,
              ),
              Expanded(
                child: new Text(title,
                    style: new TextStyle(
                        fontWeight: FontWeight.normal,
                        fontSize: 15.0,
                        color: Color(0xFF333333))),
                flex: 1,
              ),
              new Image.asset(
                "images/icon_more.png",
                width: 10.0,
                height: 10.0,
              ),
            ],
          ),
        ),
        onTap: () {
          switch (type) {
            case 0:
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => MyTreasureBox()));
              break;
            case 1:
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => SecurityCentre()));
              break;
            case 2:
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => HelpCentre()));
              break;
            case 3:
              showModalBottomSheet(
                  context: context,
                  builder: (BuildContext context) {
                    return showShare(context);
                  });
              break;
            case 4:
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => AboutUs()));
              break;
            case 5:
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => VersionUpdatePage()));
              break;

            default:
              break;
          }
        });
  }

  /// 分享弹框

  Widget showShare(BuildContext context) {
    return new Container(
      height: 150.0,
      color: Colors.white,
      child: new Column(
        children: <Widget>[
          new Padding(
            padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
            child: new Container(
              height: 100.0,
              child: new GridView.builder(
                gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    mainAxisSpacing: 5.0,
                    childAspectRatio: 1.0),
                itemBuilder: (BuildContext context, int index) {
                  return new Column(
                    children: <Widget>[
                      new GestureDetector(
                        child: new Padding(
                            padding: EdgeInsets.fromLTRB(0.0, 6.0, 0.0, 6.0),
                            child: new Image.asset(
                              'images/${urlItems[index]}',
                              width: 50.0,
                              height: 50.0,
                              fit: BoxFit.fill,
                            )),
                        onTap: () {
                          _addOverlay(context, index);
                        },
                      ),
                      new Text(nameItems[index])
                    ],
                  );
                },
                itemCount: nameItems.length,
              ),
            ),
          ),
          new GestureDetector(
            child: new Center(
              child: new Padding(
                  padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 8.0),
                  child: new Text(
                    '取  消',
                    style: new TextStyle(fontSize: 18.0, color: Colors.black),
                  )),
            ),
            onTap: () {
              Navigator.pop(context);
            },
          )
        ],
      ),
    );
  }

  /// Toast 效果

  void _addOverlay(BuildContext context, int type) async {
    //获取OverlayState
    OverlayState overlayState = Overlay.of(context);
    //创建OverlayEntry
    OverlayEntry _overlayEntry = OverlayEntry(
        builder: (BuildContext context) => Positioned(
          child: new Center(
            child: Container(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                  child: new Text(
                    type == 0
                        ? '微信'
                        : (type == 1 ? '朋友圈' : (type == 2 ? '新浪微博' : 'QQ')),
                    style: TextStyle(color: Colors.red, fontSize: 16.0),
                  ),
                ),
              ),
            ),
          ),
        ));
    Navigator.pop(context);
    //显示到屏幕上。
    overlayState.insert(_overlayEntry);
    //等待2秒
    await Future.delayed(Duration(seconds: 2));
    //移除
    _overlayEntry.remove();
  }

  /// 网络获取数据
  Future _loadData(String userId) async {
    String url = NetAddress.myPersonal;
    var data = {'userId': userId};
    var respone = await HttpUtil().post(url, data: data);
    setState(() {
      minebean _minebean = minebean.fromJson(json.decode(respone));
      mTotalAssets = _minebean.result.totalAsset;
      mCapital = _minebean.result.regularSum;
      mEarnings = _minebean.result.available;
      mNickName = _minebean.result.nickName;
      mHeadImgUrl = _minebean.result.headImgUrl;
      if (_minebean.result.authStatus == 1) {
        mText_Authentication = "身份认证 | 已认证";
      } else {
        mText_Authentication = "身份认证 | 未认证";
      }

      print(_minebean.result.headImgUrl);
    });
  }
}
